import { Message } from "@arco-design/web-vue";


const getFileName = (url: string) => {
  const num = url.lastIndexOf('/') + 1
  let fileName = url.substring(num)
  fileName = decodeURI(fileName.split('?')[0])
  return fileName
}


export function downloadByUrl({
  url,
  target = '_blank',
  fileName
}: {
  url: string
  target?: '_self' | '_blank'
  fileName?: string
}): Promise<boolean> {
  const isSameHost = new URL(url).host == location.host
  return new Promise<boolean>((resolve, reject) => {
    if (isSameHost) {
      const link = document.createElement('a')
      link.href = url
      link.target = target

      if (link.download !== undefined) {
        link.download = fileName || getFileName(url)
      }

      if (document.createEvent) {
        const e = document.createEvent('MouseEvents')
        e.initEvent('click', true, true)
        link.dispatchEvent(e)
        return resolve(true)
      }

      if (url.indexOf('?') === -1) {
        url += '?download'
      }

      window.open(url, target)
      return resolve(true)
    } else {
      const canvas = document.createElement('canvas')
      const img = document.createElement('img')
      img.setAttribute('crossOrigin', 'Anonymous')
      img.src = url
      img.onload = () => {
        canvas.width = img.width
        canvas.height = img.height
        const context = canvas.getContext('2d')!
        context.drawImage(img, 0, 0, img.width, img.height)
        canvas.toBlob((blob) => {
          const link = document.createElement('a')
          if (!blob) return
          link.href = window.URL.createObjectURL(blob)
          link.download = getFileName(url)
          link.click()
          URL.revokeObjectURL(link.href)
          resolve(true)
        }, 'image/jpeg')
      }
      img.onerror = (e) => reject(e)
    }
  })
}


export const documentFlow = (docFlow:any, name:string, suffix:string) => {
  if (!docFlow) {
    return Message.error("文档数据异常");
  }
  if (!name) {
    return Message.error("请传入文档名");
  }
  if (!suffix) {
    return Message.error("请传入文档后缀名");
  }
  try {
    let url = window.URL.createObjectURL(new Blob([docFlow])),
        fileName = name + "." + suffix,
        link = document.createElement("a");
    link.style.display = "none";
    link.href = url;
    link.setAttribute("download", fileName);
    document.body.appendChild(link);
    link.click();
    setTimeout(() => {
      URL.revokeObjectURL(link.href);
      document.body.removeChild(link);
    }, 1000);
  } catch (err) {
    alert(JSON.stringify(err));
  }
};
